//
//  ViewController.m
//  JavascriptTest
//
//  Created by yao zhaofeng on 2018/10/29.
//  Copyright © 2018 YaoZhaofeng. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WKWebView.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    JSContext *context = [[JSContext alloc] init];
    context.name = @"yzf.context";
    [context setExceptionHandler:^(JSContext *context, JSValue *exception) {
        NSLog(@"context'name is %@", context.name);
        NSLog(@"exception is %@", exception);
    }];
    
    NSString *addjs = @"function add(a, b) {return (a + b)}; add(1,4)";
    JSValue *sumValue = [context evaluateScript:addjs withSourceURL:[NSURL URLWithString:@"add.js"]];
//    NSLog(@"sum: %@", @([sumValue toInt32]));
    
    addjs = @"function add(a, b) { return (a + b)}; console.log('yaozhaofeng' + add(4,5)); add(4,5);";
    sumValue = [context evaluateScript:addjs withSourceURL:[NSURL URLWithString:@"add.js"]];
    NSLog(@"result:%@", sumValue);
    
    JSValue *resultValue = [context[@"add"] callWithArguments:@[@3, @6]];
//    NSLog(@"resultValue:%@", @([resultValue toInt32]));
    
    context[@"multiply"] = ^(NSInteger a, NSInteger b){
        return a * b;
    };
    
    addjs = @"function add(a, b) { return (a + b)}; let result = multiply(4,5); console.log('yaozhaofeng' + add(4,result)); add(4,result);";
    sumValue = [context evaluateScript:addjs withSourceURL:[NSURL URLWithString:@"add.js"]];
    NSLog(@"result:%@", sumValue);
    
//    WKWebView *webView = [[WKWebView alloc] init];
//    [webView evaluateJavaScript:@"function add(a, b) {return (a + b)}; add(1,4)" completionHandler:^(id _Nullable, NSError * _Nullable error) {
//
//    }];
}


@end
